<template>
  <!-- 添加顶级容器以确保完全控制页面渲染 -->
  <div class="login-full-page">
    <div class="login-container">
      <div class="login-wrap">
        <div class="login-box">
          <div class="logo-container">
            <img :src="systemConfig.logo" alt="系统logo" class="logo" />
            <h1>直律案管系统</h1>
          </div>
          <div class="form-container">
            <el-form
              ref="formRef"
              :model="formState"
              :rules="rules"
              size="large"
              @keyup.enter="handleLogin"
            >
              <el-form-item prop="username">
                <el-input
                  v-model="formState.username"
                  placeholder="请输入账户或手机号码"
                  prefix-icon="el-icon-user"
                ></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="formState.password"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="el-icon-lock"
                ></el-input>
              </el-form-item>
              <el-form-item prop="captcha">
                <div class="captcha-group">
                  <el-input
                    v-model="formState.captcha"
                    placeholder="请输入验证码"
                    prefix-icon="el-icon-check"
                  ></el-input>
                  <div class="captcha-container">
                    <img
                      v-if="captchaUrl"
                      :src="captchaUrl"
                      @click="refreshCaptcha"
                      class="captcha-image"
                      alt="验证码"
                      @error="handleCaptchaError"
                    />
                    <div v-else class="captcha-loading">加载中...</div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="handleLogin"
                  :loading="loading"
                  class="login-btn"
                  style="width: 100%"
                >
                  登录系统
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="footer-text">
            <span>企业数字化 · 协同办公平台</span>
          </div>
        </div>
      </div>
      <div class="foot">
        <span>Copyright © 2022-2024 直律OA. Powered by Google-OpenFE.</span>
        <br />
        <a :href="systemConfig.icp_link" target="_blank">{{ systemConfig.icp }}</a>
        |
        <a :href="systemConfig.beian_link" target="_blank">{{ systemConfig.beian }}</a>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { useUserStore } from '@/store/user'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import request from '@/utils/request'
  import config from '@/config/index'
  import { useMenuStore } from '@/store/menu'
  import { login } from '@/services/auth'

  const formRef = ref<any>(null)
  const loading = ref<boolean>(false)
  // 无状态验证码相关状态
  const captchaUrl = ref('')
  const captchaToken = ref('') // 新增：验证码token
  const captchaRetryCount = ref(0)
  const MAX_CAPTCHA_RETRIES = 3
  const isErrorHandled = ref(false)
  let isFetchingCaptcha = false
  const isShowCaptcha = ref<boolean>(true)

  const systemConfig = ref<any>({
    logo: '/static/images/logo.png',
    version: '1.0',
    icp: '浙ICP备xxxxxx号',
    beian: '浙公网安备 xxxxxx号',
    icp_link: 'https://beian.miit.gov.cn/',
    beian_link: 'http://www.beian.gov.cn/portal/registerSystemInfo',
  })

  const formState = reactive({
    username: '',
    password: '',
    captcha: '',
  })

  const rules = {
    username: [
      {
        required: true,
        message: '请输入账户或手机号码',
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      },
    ],
    captcha: [
      {
        required: true,
        message: '请输入验证码',
        trigger: 'blur',
      },
    ],
  }

  const userStore = useUserStore()
  const router = useRouter()

  /**
   * 获取无状态验证码
   */
  const getCaptcha = async () => {
    if (isFetchingCaptcha) return

    // 如果已经达到最大重试次数，不再自动重试
    if (captchaRetryCount.value >= MAX_CAPTCHA_RETRIES) {
      ElMessage.error('验证码获取失败，请手动点击刷新重试')
      return
    }

    isFetchingCaptcha = true
    try {
      // 清理旧的Blob URL，防止内存泄漏
      if (captchaUrl.value && captchaUrl.value.startsWith('blob:')) {
        URL.revokeObjectURL(captchaUrl.value)
      }

      // 使用无状态验证码接口
      const res: any = await request.get('/api/captcha/stateless')

      if (res && res.code === 0 && res.data) {
        captchaUrl.value = res.data.image // 已经是base64格式
        captchaToken.value = res.data.token // 保存token
        captchaRetryCount.value = 0 // 成功后重置计数器
      } else {
        throw new Error('获取验证码数据失败')
      }

      if (res && res.code === 0 && res.data) {
        console.log('验证码数据解析:', {
          hasImage: !!res.data.image,
          hasToken: !!res.data.token,
          imagePrefix: res.data.image ? res.data.image.substring(0, 50) + '...' : 'undefined',
          tokenLength: res.data.token ? res.data.token.length : 0,
        })

        captchaUrl.value = res.data.image // 已经是base64格式
        captchaToken.value = res.data.token // 保存token
        captchaRetryCount.value = 0 // 成功后重置计数器

        console.log('验证码设置完成:', {
          urlSet: !!captchaUrl.value,
          tokenSet: !!captchaToken.value,
        })
      } else {
        console.error('验证码响应格式错误:', {
          hasRes: !!res,
          code: res?.code,
          hasData: !!res?.data,
          fullResponse: res,
        })
        throw new Error('获取验证码数据失败 - 响应格式不正确')
      }
    } catch (error) {
      let errorMessage = '获取验证码失败'
      captchaRetryCount.value++

      const errorObj = error as any
      if (errorObj.message) {
        errorMessage = errorObj.message
      } else if (errorObj.code) {
        switch (errorObj.code) {
          case 'ECONNABORTED':
            errorMessage = '请求超时，请稍后重试'
            break
          case 'ECONNREFUSED':
            errorMessage = '服务器连接被拒绝，请确认后端服务已启动'
            break
          case 'ERR_NETWORK':
            errorMessage = '网络连接错误，请检查后端服务地址'
            break
          default:
            errorMessage = `验证码请求错误(${errorObj.code})`
        }
      }

      // 只在未达到最大重试次数时重试
      if (captchaRetryCount.value < MAX_CAPTCHA_RETRIES) {
        // 延迟重试
        setTimeout(() => {
          getCaptcha()
        }, 1500)
      } else {
        // 达到最大重试次数，停止自动重试
        ElMessage.error('验证码获取失败，请手动点击刷新重试')
      }
    } finally {
      isFetchingCaptcha = false
    }
  }

  /**
   * 处理验证码图片加载错误
   */
  const handleCaptchaError = (event: Event) => {
    // 避免触发多次错误事件
    if (isErrorHandled.value) return
    isErrorHandled.value = true

    // 只有在不是初始状态时才显示错误信息和刷新
    if (captchaUrl.value !== '') {
      captchaRetryCount.value++
      // 使用备用图片URL显示错误图标
      const target = event.target as HTMLImageElement
      if (target) {
        // 保存原始src以便后续刷新
        const originalSrc = captchaUrl.value
        // 使用错误图标临时替代
        target.src =
          ''

        // 设置一个短暂的计时器重置错误标志
        setTimeout(() => {
          isErrorHandled.value = false

          if (captchaRetryCount.value < MAX_CAPTCHA_RETRIES) {
            // 延迟重试
            window.setTimeout(() => {
              // 检查验证码URL是否为Blob URL，如果是则释放
              if (originalSrc && originalSrc.startsWith('blob:')) {
                try {
                  URL.revokeObjectURL(originalSrc)
                } catch (e) {}
              }

              // 重新获取验证码
              getCaptcha()
            }, 1000)
          } else {
            // 达到最大重试次数，停止自动重试
            ElMessage.error('验证码加载失败，请手动点击刷新重试')
          }
        }, 500)
      }
    }
  }

  /**
   * 手动刷新验证码
   * 用户点击验证码图片时调用此方法
   */
  const refreshCaptcha = () => {
    // 手动刷新时重置重试计数器和错误处理状态
    captchaRetryCount.value = 0
    isErrorHandled.value = false

    // 检查验证码URL是否为Blob URL，如果是则释放
    if (captchaUrl.value && captchaUrl.value.startsWith('blob:')) {
      try {
        URL.revokeObjectURL(captchaUrl.value)
        captchaUrl.value = '' // 清空URL，显示加载状态
      } catch (e) {}
    }

    // 显示加载中提示
    ElMessage.info('正在刷新验证码...')

    // 调用获取验证码方法
    setTimeout(() => {
      getCaptcha()
    }, 100)
  }

  /**
   * 登录处理函数 - 严格按照时序要求执行
   * 修复要点:
   * 1. 确保token、用户信息、菜单数据按顺序完整保存
   * 2. 在跳转前完成所有数据的加载和验证
   * 3. 使用isLogin标记控制登录状态
   */
  const handleLogin = async (): Promise<void> => {
    if (!formRef.value) return

    loading.value = true
    try {
      // 验证表单
      await formRef.value.validate()

      // 步骤1: 清除旧数据，确保登录状态干净
      localStorage.clear()
      userStore.token = null
      userStore.userInfo = {
        id: 0,
        name: '',
        username: '',
        role: '',
        deptId: 0,
        deptName: '',
      } as any
      userStore.isLogin = false

      // 步骤2: 执行登录请求
      const loginData = {
        username: formState.username,
        password: formState.password,
        captcha: formState.captcha,
        captcha_token: captchaToken.value,
      }

      const loginResult = await login(loginData)

      if (loginResult.code !== 0) {
        throw new Error(loginResult.msg || '登录失败')
      }

      // 步骤3: 保存token - 必须先设置token才能进行后续API调用
      const token = loginResult.data.token
      if (!token) {
        throw new Error('未获取到登录凭证')
      }

      userStore.setToken(token)
      localStorage.setItem('token', token)

      // 步骤4: 处理用户信息
      const rawUserInfo = loginResult.data.user_info
      if (!rawUserInfo || !rawUserInfo.id) {
        throw new Error('用户信息不完整')
      }

      const userInfo: any = {
        id: rawUserInfo.id,
        name: rawUserInfo.name || '', // 真实姓名
        username: rawUserInfo.username || '',
        nickname: rawUserInfo.name || rawUserInfo.nickname || rawUserInfo.username || '',
        avatar: rawUserInfo.thumb || rawUserInfo.avatar || '',
        department: rawUserInfo.department_names || rawUserInfo.department || '',
        position: rawUserInfo.position_name || rawUserInfo.position || '',
        menu: [] as any[], // 临时初始化，后续赋值
      }

      // 步骤5: 处理菜单数据
      const menuData = (loginResult.data as any).menu || rawUserInfo.menu || []
      if (Array.isArray(menuData)) {
        userInfo.menu = menuData

        // 保存菜单到localStorage（包含工作台）
        const workbenchMenu = {
          id: -1,
          pid: 0,
          title: '工作台',
          icon: 'HomeFilled',
          mig_src: '/home',
          component: '',
          redirect: '',
          sort: 0,
          status: 1,
        }

        const fullMenuList = [workbenchMenu, ...menuData]
        localStorage.setItem(
          'menuList',
          JSON.stringify({
            menuList: fullMenuList,
            timestamp: Date.now(),
          })
        )
      }

      // 步骤6: 保存用户信息到store和localStorage
      userStore.setUserInfo(userInfo)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))

      // 步骤7: 设置登录状态
      userStore.isLogin = true

      // 步骤8: 验证数据完整性
      const savedToken = localStorage.getItem('token')
      const savedUserInfo = localStorage.getItem('userInfo')

      if (!savedToken || !savedUserInfo) {
        throw new Error('数据保存失败，请重试')
      }

      // 步骤9: 所有数据准备完成，显示成功消息
      ElMessage.success('登录成功')

      // 步骤10: 等待一小段时间确保所有状态更新完成，然后跳转
      await new Promise(resolve => setTimeout(resolve, 100))

      // 步骤11: 跳转到首页
      await router.replace('/')
    } catch (error: any) {
      // 清理可能不完整的数据
      localStorage.clear()
      userStore.token = null
      userStore.userInfo = {
        id: 0,
        name: '',
        username: '',
        role: '',
        deptId: 0,
        deptName: '',
      } as any
      userStore.isLogin = false

      const errorMsg = error.message || error.msg || error.response?.data?.msg || '登录失败，请重试'
      ElMessage.error(errorMsg)

      // 验证码错误时刷新验证码
      if (errorMsg.includes('验证码')) {
        refreshCaptcha()
      }
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取系统配置
   */
  const getSystemConfig = async () => {
    try {
      // 这里应该调用获取系统配置的接口
      // 暂时使用默认配置
      systemConfig.value = {
        logo: '/static/images/logo.png',
        version: '1.0',
        icp: '浙ICP备xxxxxx号',
        beian: '浙公网安备 xxxxxx号',
        icp_link: 'https://beian.miit.gov.cn/',
        beian_link: 'http://www.beian.gov.cn/portal/registerSystemInfo',
      }
    } catch (error) {}
  }

  // 初始化
  onMounted(() => {
    try {
      getSystemConfig()
      // 首次加载显示加载提示
      getCaptcha()
    } catch (e) {}
  })
</script>

<style scoped>
  /* 顶级容器，确保完全覆盖页面 */
  .login-full-page {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999; /* 确保在最上层，不受其他布局影响 */
    overflow: hidden;
  }

  .login-container {
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
    padding: 20px;
    box-sizing: border-box;
  }

  .login-wrap {
    width: 100%;
    max-width: 400px;
  }

  .login-box {
    background: rgba(15, 23, 42, 0.7);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border-radius: 16px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    padding: 30px;
    box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  }

  .logo-container {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30px;
  }

  .logo {
    width: 50px;
    height: 50px;
    margin-right: 15px;
    border-radius: 50%;
    background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
    padding: 5px;
    box-shadow: 0 0 20px rgba(6, 182, 212, 0.5);
  }

  .logo-container h1 {
    font-size: 24px;
    font-weight: 700;
    margin: 0;
    background: linear-gradient(90deg, #06b6d4, #3b82f6);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
  }

  .form-container {
    width: 100%;
  }

  .captcha-group {
    display: flex;
    gap: 10px;
  }

  .captcha-group .el-input {
    flex: 1;
  }

  .captcha-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 120px;
    height: 40px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background: #f9f9f9;
  }

  .captcha-image {
    height: 40px;
    cursor: pointer;
    border-radius: 4px;
  }

  .captcha-loading {
    color: #999;
    font-size: 12px;
    text-align: center;
  }

  .login-btn {
    height: 48px;
    font-size: 16px;
    background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
    border: none;
    transition: all 0.3s ease;
  }

  .login-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 20px rgba(6, 182, 212, 0.4);
  }

  .footer-text {
    text-align: center;
    margin-top: 20px;
    color: #94a3b8;
    font-size: 12px;
  }

  .foot {
    position: fixed;
    font-size: 12px;
    bottom: 15px;
    text-align: center;
    width: 100%;
    color: #94a3b8;
  }

  .foot a {
    color: #06b6d4;
    text-decoration: none;
  }

  /* 响应式调整 */
  @media (max-width: 480px) {
    .login-box {
      padding: 20px;
    }

    .logo {
      width: 40px;
      height: 40px;
    }

    .logo-container h1 {
      font-size: 20px;
    }

    .captcha-group {
      flex-direction: column;
    }

    .captcha-image {
      width: 100%;
      height: 40px;
    }
  }

  /* 全局覆盖样式，确保登录页面不受其他样式影响 */
  .login-full-page :deep(*) {
    box-sizing: border-box;
  }

  /* 防止侧边栏和头部组件在登录页面显示 */
  .login-full-page ~ * {
    display: none !important;
  }
</style>
